package com.tutu.collect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tutu.collect.mapper.CollectMapper;
import com.tutu.collect.service.CollectService;
import com.tutu.commons.clients.ProductClient;
import com.tutu.commons.pojo.Collect;
import com.tutu.commons.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-12-20 16:48
 **/
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private ProductClient productClient;


    /**
     * 根据用户id查询用户收藏商品
     *
     * @param userId 用户id
     * @return 返回结果集合
     */
    @Override
    public List<Object> getCollectByUserId(Integer userId) {
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId, userId);
        List<Collect> collects = collectMapper.selectList(queryWrapper);
        List<Object> products = collects.stream().map((collect -> {
            R result = productClient.getProductId(collect.getProductId());
            if (R.FAIL_CODE.equals(result.getCode())) {
                return R.ok(null);
            }
            return result.getData();
        })).collect(Collectors.toList());
        return products;
    }

    /**
     * 用户添加喜欢商品
     *
     * @param collect 用户收藏实体类
     * @return 返回结果实体集
     */
    @Override
    public R saveCollect(Collect collect) {
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId, collect.getUserId());
        List<Collect> collects = collectMapper.selectList(queryWrapper);
        for (Collect col : collects) {
            if (collect.getProductId().equals(col.getProductId())) {
                return R.fail("该商品已经添加收藏,请到我的收藏查看");
            }
        }
        collectMapper.insert(collect);
        return R.ok("添加收藏成功");
    }

    /**
     * 删除收藏商品
     *
     * @param collect 用户收藏实体类
     * @return 返回结果实体集
     */
    @Override
    public int removeCollect(Collect collect) {
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId, collect.getUserId());
        queryWrapper.eq(Collect::getProductId, collect.getProductId());
        return collectMapper.delete(queryWrapper);
    }
}
